<?php

namespace app\common\logic;





use app\admin\model\Leeaddress;
use app\common\model\shop\Category;
use app\common\model\shop\Goods;
use app\common\model\shop\Order;
use app\common\utils\Utils;
use app\common\validate\shop\OrderValidate;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * Token接口
 */
class ShopLogic
{
    //分类模型
    protected $categoryModel = null;
    //商品模型
    protected $goodsModel = null;

    protected $row = 15;
    //默认排序
    public $order = [
        'weigh'=> 'desc',
        'createtime' => 'desc',
    ];
    protected $tree = null;

    protected $extraField = ['pics', 'content'];
    public function __construct()
    {
        $this->categoryModel = new Category();
        $this->goodsModel = new Goods();

        $cate = $this->categoryModel->getGoodsCategory(['status'=> 'normal']);

        $this->tree = Tree::instance()->init($cate, 'category_id');
    }

    /**
     * 设置订单
     * @return \app\common\logic\ShopLogic
     */
    public function setOrder($order) {
        foreach ($order as $k => $v) {
            if (!in_array($v, ['asc', 'desc'])) {
                throw new ValidateException('排序字段错误');
            }
        }
        if ($order) {
            $this->order = $order;
        }

        return $this;
    }



    public function getGoodsList($where, $limit = false) {
        $where['status'] = 0;
        $model = $this->goodsModel
            ->field($this->extraField, true)
            ->where($where)
            ->order($this->order);
        if ($limit !== false) {
            $list = $model->limit($limit)->select();
        } else {
            $list = $model->paginate($this->row);
        }

        return $list;
    }

    /**
     * 获取分类
     */
    public function getCategory($where = []) {
        $where['status'] = 'normal';
        $list = $this->categoryModel->where($where)->order($this->order)->select();

        return $list;
    }

    /*获取分类树形数组*/
    public function getTreeArray() {
        return $this->tree->getTreeArray(0);
    }
    /**
     * 获取分类
     * @param int $limit
     * @throws Exception
     * @return  object
     */
    public function getLimitCategory($limit = 3, $where=[],$order = []) {
        $where['status'] = 'normal';
        $order = array_merge($this->order, $order);
        $list = $this->categoryModel->where($where)->order($order)->limit($limit)->select();

        return $list;
    }

    /**
     * 获取3个商品
     * @param int $limit
     * @throws Exception
     * @return  object
     */
    public function getLimitGoods($cate_id, $limit = 3) {
        $where['status'] = 0;
        $where['category_id'] = $cate_id;
        $list = $this->goodsModel->where($where)->order($this->order)->limit($limit)->field(['content', 'pics'], true)->select();

        return $list;
    }

    /**包含自身*/
    public function getChildIds($id) {
        return $this->tree->getChildrenIds($id, true);
    }

    /** 牛详情*/
    public function detail($id = 0) {
        $info = $this->goodsModel->where('id', $id)->find();
        if (!$info) {
            throw new ValidateException('未获取到详情');
        }

        //获取牛详情的时候需要记录足迹
        if (defined('UID') && UID > 0) {
            $where['user_id'] = UID;
            $where['goods_id'] = $id;
            $count = Db::name('custom_foot')->where($where)->count();
            if ($count > 0) {
                //如果有记录了就更新添加时间
                Db::name('custom_foot')->where($where)->setField('createtime', time());
            } else {
                Db::name('custom_foot')->insert([
                    'user_id' => UID,
                    'goods_id' => $id,
                    'createtime' => time()
                ]);
            }
        }

        //富文本路径替换
        $info['content'] = Utils::richTextAbsoluteUrl( $info['content'], request()->domain());
        return $info;
    }

    /**
     * 收获地址
     */
    public function getAddress($address_id) {
        $info = Leeaddress::get($address_id);
        if (!$info) {
            throw new ValidateException('地址id错误');
        }
        return $info;
    }

    public function submit() {
        (new OrderValidate())->goCheck();
        $param = request()->param();
        $param['user_id'] = UID;
        $type = input('type/d', 0);
        $id = input('id/d', 0);

        if (!$param['use_time']) {
            $param['use_time'] = 0;
        } else {
            $param['use_time'] = strtotime($param['use_time']);
        }
        Db::startTrans();
        try {
            unset($param['type']);
            if ($type == 1 && $id == 0) {
                throw new ValidateException('参数错误');
            }
            if ($type == 1) {
                $res = (new Order())
                    ->allowField(true)
                    ->save($param, ['id' => $id]);
            } else {
                unset($param['id']);
                $res = (new Order())
                    ->allowField(true)
                    ->data($param)->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            throw new ValidateException($e->getMessage());
        }



        //提交订单成功
        $salesman_id = input('salesman_id/d', 0);

        return true;
    }

    //我的预定
    public function getOrders($where) {
        $list = (new Order())
            ->where($where)
            ->order('createtime desc')
            ->paginate($this->row)
            ->each(function($item, $key) {
                $item->goods_info = $this->goodsModel
                    ->field(['content', 'pics', 'deletetime'], true)->find($item['goods_id']);
            });

        return $list;
    }

    /**
     * 收藏
     */
    public function collect($id, $user_id) {
       if (!$id) {
           throw new ValidateException('参数错误');
       }

       $data = [
           'user_id' => $user_id,
           'goods_id' => $id,
       ];

       $count = Db::name('shop_collect')->where($data)->count();
       if ($count > 0) {
           throw new ValidateException('已经收藏过');
       }

       $data['createtime'] = time();
       Db::name('shop_collect')->insert($data);

       return true;
    }

    /**
     * 是否收藏
     */
    public function isCollect($id, $user_id = 0) {
        if (!$id) {
            throw new ValidateException('参数错误');
        }
        if (!$user_id) {
            return 0;
        }
        $data = [
            'user_id' => $user_id,
            'goods_id' => $id,
        ];

        $count = Db::name('shop_collect')->where($data)->count();
        if ($count > 0) {
            return 1;
        } else {
            return 0;
        }

    }

    /**
     * 删除订单接口
     */
    public function del($id = 0) {
        if (!$id) {
            throw new ValidateException('参数错误');
        }
        $order = Order::get($id);
        if (!$order) {
            throw new ValidateException('参数错误');
        }

        if ($order['type'] != 0) {
            throw new ValidateException('订单已被管理人员处理，不能删除');
        }
        Db::startTrans();
        try {

            $order->delete();
            $this->goodsModel->where(['id' => $order['goods_id']])->setInc('stock', $order['num']);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());

        }
        return true;
    }

    /**
     * 获取订单详情
     */
    public function orderDetail($id = 0){
        $order = Order::get($id);
        if (!$order) {
            throw new ValidateException('订单不存在');
        }

        $good = Goods::get($order['goods_id']);
        $good->hidden(['content', 'pics']);
        $order['goods_info'] = $good;

        if ($order['type'] != 0) {
            $order['is_delete'] = 0; //代表不可删除
        } else {
            $order['is_delete'] = 1; //代表可以删除
        }

        return $order;
    }
}
